import React, { useEffect, useState, useRef } from 'react'
import { Button, View, Image, Input, Text, Textarea } from '@tarojs/components'
import Taro, { onAppHide, requirePlugin } from '@tarojs/taro'
import { getNavTop, getFullSrcs } from '@/utils/Helper'
import { AtActionSheet, AtActionSheetItem } from 'taro-ui'
import styles from './index.module.scss'

// 引入插件
export default function CustomerService(props) {
  const [btnText, setBtnText] = useState('按住 说话')
  //录音配置
  const [config, setConfig] = useState<any>({})
  const [iptValue, setIptValue] = useState<string>('')
  const [fileList, setFileList] = useState<any>([])
  //录音列表
  const flag = useRef<boolean>(true)

  const [buttonStates, setButtonStates] = useState({
    deepThink: true,
    webSearch: false,
    moreState: false
  })
  const [fileVisible, setFileVisible] = useState(false)
  const handleButtonClick = async (buttonType) => {
    if (buttonType === 'webSearch' && fileList.length) {
      return
    }
    setButtonStates((prev) => {
      props.btnFun(buttonType, !prev[buttonType])
      return {
        ...prev,
        [buttonType]: !prev[buttonType] // 切换当前按钮的状态
      }
    })
  }

  const [imgUrl, setImgUrl] = useState<any>(
    'http://111.34.82.98:10001/talent/files/37bbe8be-678f-4a80-a316-2ddca3b261b9/voice.png'
  )

  const imgClick = () => {
    props.changeHeight(0, 'keyboardBottom')
    if (flag.current) {
      setImgUrl('http://111.34.82.98:10001/talent/files/d57ef16f-31bc-47c1-8e7e-66b3d01e2f45/keyboard.png')
      flag.current = false
    } else {
      setImgUrl('http://111.34.82.98:10001/talent/files/37bbe8be-678f-4a80-a316-2ddca3b261b9/voice.png')
      flag.current = true
    }
  }
  const inputConfirm = () => {
    props.emitDataList({
      files: fileList,
      content: iptValue,
      role: 'USER',
      type: 'text'
    })
    setFileList([])
    setIptValue('')
  }
  const iptFun = (e) => {
    setIptValue(e.detail.value)
  }
  const onFocus = (e) => {
    console.log(e.detail.height, 'onFocusonFocusonFocusonFocusonFocus')
    props.changeHeight(e.detail.height, 'keyboardBottom')
  }
  const onBlur = (e) => {
    console.log(e.detail.height, 'onBluronBluronBluronBlur')
    props.changeHeight(e.detail.height, 'keyboardBottom')
  }
  const newChatFun = () => {
    props.newChatFun()
  }
  const sendClick = (val) => {
    console.log(val, 'valvalvalval')
    props.emitDataList({
      content: val.detail.value,
      files: fileList,
      role: 'USER',
      type: 'text'
    })
    setFileList([])
    setIptValue('')
  }
  //生成随机数
  function generateRandomNumber() {
    // 生成 4 位随机数，范围是 0 到 9999
    const randomPart = Math.floor(Math.random() * 10000)
    // 将随机数转换为 4 位字符串，不足 4 位时前面补 0
    const paddedRandomPart = String(randomPart).padStart(4, '0')
    // 拼接固定部分和随机部分
    return '100014' + paddedRandomPart
  }

  const cameraFun = () => {
    setFileVisible(false)
    Taro.chooseImage({
      count: 5, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function(res) {
        console.log(res.tempFiles, 'resresres')
        let list = res.tempFiles
          .map((item, index) => {
            if (item.size / 1024 / 1024 > 10) {
              Taro.showToast({
                title: '文件不能超过10M',
                duration: 2000
              })
            } else {
              return {
                url: item.path,
                size:
                  Math.floor(item.size / 1024 / 1024) >= 1
                    ? (item.size / 1024 / 1024).toFixed(2) + 'M'
                    : (item.size / 1024).toFixed(2) + 'kb',
                name: generateRandomNumber() + '.jpg',
                type: 'image'
              }
            }
          })
          .filter((item) => item)
        setFileList([...fileList, ...list])

        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        // setImgSrc(tempFilePaths);
        // let fileSystemManager = Taro.getFileSystemManager();
        // fileSystemManager.readFile({
        //   filePath: tempFilePaths,
        //   success: function (res) {
        //     console.log(res, "getFileInfogetFileInfogetFileInfo");
        //   },
        // });
      }
    })
  }
  const albumFun = () => {
    setFileVisible(false)
    Taro.chooseImage({
      count: 5, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
      success: function(res) {
        let list = res.tempFiles
          .map((item, index) => {
            if (item.size / 1024 / 1024 > 10) {
              Taro.showToast({
                title: '文件不能超过10M',
                duration: 2000
              })
            } else {
              return {
                url: item.path,
                size:
                  Math.floor(item.size / 1024 / 1024) >= 1
                    ? (item.size / 1024 / 1024).toFixed(2) + 'M'
                    : (item.size / 1024).toFixed(2) + 'kb',
                name: generateRandomNumber() + '.jpg',
                type: 'image'
              }
            }
          })
          .filter((item) => item)
        setFileList([...fileList, ...list])
      }
    })
  }
  const fileFun = () => {
    setFileVisible(false)
    Taro.chooseMessageFile({
      count: 10,
      type: 'file',
      success: function(res) {
        console.log(res, 'resresresresresres')

        // tempFilePath可以作为img标签的src属性显示图片
        // const tempFilePaths = res.tempFiles;
        // console.log(tempFilePaths, "tempFilePathstempFilePaths");
      },
      fail: (res) => {
        console.log(res, 'failfailfailfailfail')
      }
    })
  }
  const handleCancel = (index) => {
    setFileList((preList) => {
      return preList.filter((item, i) => {
        return i !== index
      })
    })
  }
  return (
    <View className={styles['bottomBtn']}>
      {props.dataList[0]?.content ? (
        <View className={styles['new-chat']} onClick={newChatFun}>
          <Image className={styles['new-chat-img']} src={getFullSrcs('documents/plus.jpg')} />
          <View className={styles['new-chat-text']}>开启新对话</View>
        </View>
      ) : (
        ''
      )}
      <View className={styles['img_list']}>
        {fileList.map((item, index) => {
          return (
            <View className={styles['img_list_item']} key={index}>
              <Image src={getFullSrcs('documents/upingimg.jpg')}></Image>
              <View className={styles['img_list_item_text']}>
                <View className={styles['img_list_item_text_title']}>{item.name}</View>
                <View className={styles['img_list_item_text_size']}>{item.size}</View>
              </View>
              <View className={styles['img_list_item_cancel']} onClick={(e) => handleCancel(index)}>
                ✕
              </View>
            </View>
          )
        })}
      </View>
      <View className={styles['inputArea']}>
        <Image style='width: 50rpx;height: 50rpx' src={imgUrl} onClick={imgClick} />
        {flag.current ? (
          <>
            <Textarea
              cursorSpacing={5}
              value={iptValue}
              onInput={iptFun}
              adjust-position={false}
              style={{ width: iptValue ? '73%' : '90%' }}
              onFocus={onFocus}
              onBlur={onBlur}
              className={styles['input']}
              placeholder='给 中优 发送消息'
              maxlength={2048}
              onConfirm={sendClick}
              showConfirmBar={false}
              autoHeight
              disabled={props.timeOver}
            />
            {iptValue ? (
              <Button size='mini' className={styles['sendBtn']} onClick={inputConfirm}>
                发送
              </Button>
            ) : (
              ''
            )}
          </>
        ) : (
          <></>
        )}
      </View>
      <View className={styles['buttonGroup']}>
        <View
          className={`${styles['button']} ${buttonStates.deepThink ? styles['active'] : ''}`}
          onClick={() => handleButtonClick('deepThink')}
        >
          <Image
            src={
              buttonStates.deepThink
                ? 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/network1.png'
                : 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/network2.png'
            }
          />
          深度思考（R1）
        </View>
        <View
          className={`${styles['button']} ${
            fileList.length ? styles['disabled'] : buttonStates.webSearch ? styles['active'] : ''
          }`}
          onClick={() => handleButtonClick('webSearch')}
          // style={{ color: fileList.length ? '#B5B6BD' : '#333' }}
        >
          <Image
            src={
              //有文件的时候 button 颜色为灰色
              fileList.length
                ? 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/1344964294139318272.jpg'
                : buttonStates.webSearch
                ? 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/deep1.png'
                : 'https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/deep2.png'
            }
          />
          联网搜索
        </View>
        <Image
          onClick={() => setFileVisible(true)}
          className={styles['more-btn']}
          src='https://storage-backup001-001.jingxizhigu.cn/jxzg-park-service-ar/1344964116233719808.jpg'
        />
      </View>
      <AtActionSheet isOpened={fileVisible} cancelText='取消' onClose={() => setFileVisible(false)}>
        <AtActionSheetItem onClick={cameraFun}>选择拍摄图片</AtActionSheetItem>
        <AtActionSheetItem onClick={albumFun}>选择会话中的图片</AtActionSheetItem>
        <AtActionSheetItem onClick={fileFun}>选择会话中的文档</AtActionSheetItem>
      </AtActionSheet>
      {/* {buttonStates.moreState && (
        <View className={styles['more-btn-content']} id='photosid'>
          <View className={styles['more-btn-box']} onClick={cameraFun}>
            <View className={styles['more-btn-img']}>
              <Image src={getFullSrcs('documents/tprt.jpg')}></Image>
            </View>
            <Text>拍照识文字</Text>
          </View>
          <View className={styles['more-btn-box']} onClick={albumFun}>
            <View className={styles['more-btn-img']}>
              <Image src={getFullSrcs('documents/lprt.jpg')}></Image>
            </View>
            <Text>图片识文字</Text>
          </View>
          <View className={styles['more-btn-box']} onClick={fileFun}>
            <View className={styles['more-btn-img']}>
              <Image src={getFullSrcs('documents/upfiles.jpg')}></Image>
            </View>
            <Text>文件</Text>
          </View>
        </View>
      )} */}
    </View>
  )
}
